package eu.codlab.twitteirb;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import eu.codlab.twitteirb.manage.url.LoadURL;

import android.os.AsyncTask;

public class AvatarManager {
	private HashMap<String, byte[]> _avatars;
	private String _cookie;
	private TwittEirbService _master;

	public AvatarManager(TwittEirbService master){
		_master = master;
		_avatars=new HashMap<String, byte[]>();
	}

	public byte[] getAvatar(String login){
		if(_avatars.containsKey(login))
			return _avatars.get(login);
		return null;
	}

	public void setCookie(String cookie){
		_cookie = cookie;
	}

	public void addLogin(String login){
		if(!_avatars.containsKey(login))
			_avatars.put(login, null);
	}

	private class DownloadAsync extends AsyncTask<Integer, String, Object>{

		byte [] getAvatar(String login){
			//Log.d("downloading",login);
			//Log.d("cookie",_cookie+";");
			String[] headers = new String[]{
					"Host","trombi-dev.eirb.fr",
					"User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1",
					"Accept","image/png,image/*;q=0.8,*/*;q=0.5",
					"Accept-Language","fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3",
					"Accept-Encoding","gzip, deflate",
					"Connection","keep-alive",
					"Referer","http://twitt.eirb.fr/",
					"Cookie",_cookie+";"
			};
			LoadURL chargement = new LoadURL("http://trombi-dev.eirb.fr/api/small/"+login);
			ByteArrayOutputStream ostream = chargement.loadGetUrlByte(headers);
			//Log.d("ss",ostream.toString());
			byte [] ret = ostream.toByteArray();
			return ret;
		}
		@Override
		protected Object doInBackground(Integer... params) {
			Set<Entry<String, byte[]>> infos = _avatars.entrySet();
			Iterator<Entry<String, byte[]>> iterator = infos.iterator();
			while(iterator.hasNext()){
				Entry<String,byte[]> entry = iterator.next();
				//Log.d("fetching",entry.getKey());
				if(entry!=null && entry.getValue() == null){
					byte [] data = this.getAvatar(entry.getKey());
					_avatars.put(entry.getKey(), data);
				}
			}
			_master.onAvatarLoaded();
			return null;
		}

	}

	public void go(){
		DownloadAsync s = new DownloadAsync();
		s.execute(new Integer[]{1});
	}
}
